package top.jacktgq.utils;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * hikari数据库连接池工具类
 */
public class HikariUtils {
    // 获得Connection，从连接池中获取
    private static HikariDataSource datasource;
    // 创建ThreadLocal对象
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    static {
        InputStream in = null;
        try {
            in = HikariDataSource.class.getResourceAsStream("/jdbc.properties");
            Properties props = new Properties();
            props.load(in);
            datasource = new HikariDataSource(new HikariConfig(props));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 开启事务
    public static void startTransaction() throws SQLException {
        getConnection().setAutoCommit(false);
    }

    // 回滚事务
    public static void rollbackTransaction() throws SQLException {
        getConnection().rollback();
    }

    // 提交事务
    public static void commitTransaction() throws SQLException {
        getConnection().commit();
        tl.remove();
    }

    // 控制事务的时候用该方法
    public static Connection getConnection() throws SQLException {
        // 从ThreadLocal对象中寻找当前线程上是否有对应的Connection对象
        Connection conn = tl.get();
        // 如果ThreadLocal中没有Connection对象
        if (conn == null) {
            // 获得新的Connection
            conn = getCurrentConnection();
            // 将Connection资源绑定到ThreadLocal(map)上
            tl.set(conn);
        }
        return conn;
    }

    // 不需要控制事务的时候获取连接池即可
    public static DataSource getDataSource() {
        return datasource;
    }

    // 内部调用该方法
    public static Connection getCurrentConnection() throws SQLException {
        return datasource.getConnection();
    }

    /*public static void main(String[] args) throws SQLException {
        QueryRunner runner = new QueryRunner(HikariUtils.getDataSource());
        List<Map<String, Object>> result = runner.query("select * from student", new MapListHandler());
        result.forEach(System.out::println);
    }*/
}
